package com.yhy.server.service;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.yhy.autoconfig.templates.AipFaceTemplate;
import com.yhy.autoconfig.templates.HuanXinTemplate;
import com.yhy.autoconfig.templates.OssTemplate;
import com.yhy.autoconfig.templates.SmsTemplate;
import com.yhy.domain.User;
import com.yhy.domain.UserInfo;
import com.yhy.domain.mongo.RecommendUser;
import com.yhy.domain.vo.PageResult;
import com.yhy.domain.vo.UserInfoVo;
import com.yhy.domain.vo.UserLikeListVo;
import com.yhy.dubbo.api.UserApi;
import com.yhy.domain.vo.ErrorResult;
import com.yhy.dubbo.api.UserInfoApi;
import com.yhy.dubbo.api.mongo.FriendApi;
import com.yhy.dubbo.api.mongo.RecommendUserApi;
import com.yhy.dubbo.api.mongo.UserLikeApi;
import com.yhy.dubbo.api.mongo.VisitorsApi;
import com.yhy.server.interceptor.UserHolder;
import com.yhy.server.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;


import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

@Service
public class UserService {

    @Reference
    private UserApi userApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private UserLikeApi userLikeApi;

    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private VisitorsApi visitorsApi;

    @Reference
    private FriendApi friendApi;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public ResponseEntity findByMobile(String mobile) {
        User user = userApi.findByMobile(mobile);
        return ResponseEntity.ok(user);
    }

    public ResponseEntity saveUser(String mobile, String password) {
        User user = new User();
        user.setMobile(mobile);
        user.setPassword(password);
        return ResponseEntity.ok(null);
    }

    /**
     * 手机号登录
     *
     * @param mobile
     * @return
     */
    public ResponseEntity sendSms(String mobile) {
        //生成6位数字
//        String code = RandomUtil.randomNumbers(6);
        String code = "123456";
//        smsTemplate.sendSms(mobile,code);
        redisTemplate.opsForValue().set("CHECK_CODE" + mobile, code, Duration.ofMinutes(5));
        return ResponseEntity.ok(null);
    }

    public ResponseEntity phoneLogin(String mobile, String code) {
//        1.从redis里取验证码
        String redisCode = (String) redisTemplate.opsForValue().get("CHECK_CODE" + mobile);
//        2.判断验证码是否存在 是否正确
        if (redisCode == null || !redisCode.equals(code)) {
            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }
        redisTemplate.delete("CHECK_CODE" + mobile);
//        3.根据手机号查找用户
        User user = userApi.findByMobile(mobile);
//        3.1如果用户不存在就创建用户
        boolean isNew = false;
        String type = "0101";
        if (user == null) {
            user = new User();
            user.setMobile(mobile);
            user.setPassword("qqqqqq");
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;
            //新用户注册到环信
            huanXinTemplate.register(id);
            //新用户本次操作类型为注册0102
            type="0102";
        }
        //构造操作日志 传递给中间件
        Map message = new HashMap();
        message.put("userId",user.getId());
        message.put("type",type);
        message.put("date",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

        rocketMQTemplate.convertAndSend("tanhua-logs",message);

        //生成token
        String token = JwtUtils.createToken(mobile, user.getId());
        String jsonString = JSON.toJSONString(user);
        redisTemplate.opsForValue().set("TOKEN__" + token, jsonString, Duration.ofHours(1));
        Map map = new HashMap();
        map.put("token", token);
        map.put("isNew", isNew);
        return ResponseEntity.ok(map);
    }

    /**
     * 用户
     *
     * @param userInfo
     * @param token
     * @return
     */
    public ResponseEntity saveUserInfo(UserInfo userInfo, String token) {
        User user = UserHolder.getUser();
        ;
        userInfo.setId(user.getId());
        userInfoApi.save(userInfo);
        return ResponseEntity.ok(null);
    }

    /**
     * 从token中获取当前User
     *
     * @param token
     * @return
     */
    public User getUserByToken(String token) {
        String jsonUser = (String) redisTemplate.opsForValue().get("TOKEN__" + token);
        if (StringUtils.isEmpty(jsonUser)) {
            return null;
        } else {
            return JSON.parseObject(jsonUser, User.class);
        }
    }

    public ResponseEntity updateUserHead(MultipartFile headPhoto, String token) throws IOException {
//        1.验证是否包含人脸
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());
        if (!detect) {
            return ResponseEntity.status(500).body(ErrorResult.faceError());
        }
//        2.包含人脸，上传图片至OSS，并保存url到userinfo表avatar
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        User user = UserHolder.getUser();
        ;
        UserInfo userInfo = userInfoApi.findById(user.getId());
        userInfo.setAvatar(imageUrl);
        userInfoApi.update(userInfo);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity findUserInfo(String token) {
        User user = UserHolder.getUser();
        ;

        UserInfo userInfo = userInfoApi.findById(user.getId());

        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        userInfoVo.setAge(userInfo.getAge() == null ? "18" : userInfo.getAge().toString());
        return ResponseEntity.ok(userInfoVo);
    }

    public ResponseEntity updateUserInfo(UserInfo userInfo, String token) {
        User user = UserHolder.getUser();
        ;

        userInfo.setId(user.getId());

        userInfoApi.update(userInfo);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity updateUserInfoHeader(MultipartFile headPhoto, String token) throws IOException {
//        1.先判断有没有人脸信息
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());
        if (!detect) {
            return ResponseEntity.status(500).body(ErrorResult.faceError());
        }
//        2.有人脸信息,开始保存图片到OSS,并修改UserInfo中的avatar
        String newImageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        User user = UserHolder.getUser();
        ;
        UserInfo userInfo = userInfoApi.findById(user.getId());
        userInfo.setAvatar(newImageUrl);
        userInfoApi.update(userInfo);
        return ResponseEntity.ok(null);
    }

    /**
     * 查看我的喜欢统计数据
     *
     * @return
     */
    public ResponseEntity counts() {
        Long userId = UserHolder.getUserId();
        Long eachLoveCount = userLikeApi.queryEachLoveCount(userId);
        Long loveCount = userLikeApi.queryLoveCount(userId);
        Long fanCount = userLikeApi.queryFanCount(userId);

        Map map = new HashMap();
        map.put("eachLoveCount", eachLoveCount);
        map.put("loveCount", loveCount);
        map.put("fanCount", fanCount);
        return ResponseEntity.ok(map);
    }

    public ResponseEntity queryUserLikeList(Integer page, Integer pagesize, Integer type) {
//        1.获取当前用户id
        Long userId = UserHolder.getUserId();
//        2.判断当前需要的数据类型 做对应的处理
        PageResult result = new PageResult();
        if (type == 1) {
            result = userLikeApi.queryEachLoveList(page, pagesize, userId);
        } else if (type == 2) {
            result = userLikeApi.queryLoveList(page, pagesize, userId);
        } else if (type == 3) {
            result = userLikeApi.queryFanList(page, pagesize, userId);
        } else {
            result = visitorsApi.queryVisitorsList(page, pagesize, userId);
            String key = "visitors_time_" + userId;
            redisTemplate.opsForValue().set(key, System.currentTimeMillis() + "");
        }
//        3.构造返回值
        List<Long> items = (List<Long>) result.getItems();
        List<UserLikeListVo> list = new ArrayList<>();
        for (Long toUserId : items) {
            UserInfo userInfo = userInfoApi.findById(toUserId);
            RecommendUser user = recommendUserApi.findRecommendUser(toUserId, userId);
            UserLikeListVo vo = UserLikeListVo.init(userInfo, user);
            //判断是否为喜欢列表加载
            if(type == 2){
                redisTemplate.opsForValue().set("alreadyLove_" + userId + "_" + toUserId, "0");
            }
            if(redisTemplate.hasKey("alreadyLove_"+userId+"_"+toUserId)){
                vo.setAlreadyLove(true);
            }
            list.add(vo);
        }
        result.setItems(list);
        return ResponseEntity.ok(result);
    }

    public ResponseEntity fansLike(Long likeUserId) {
        Long userId = UserHolder.getUserId();
//        1.调用api保存喜欢数据 并查询是否相互喜欢
        boolean isFriend = userLikeApi.save(userId,likeUserId);
//        3.添加redis操作记录
        redisTemplate.opsForValue().set("alreadyLove_" + userId + "_" + likeUserId, "0");
//        2.如果相互喜欢 添加数据到user_like表 并配置环信好友关系
        if(isFriend){
            friendApi.addContacts(userId,likeUserId);
            huanXinTemplate.contactUsers(userId,likeUserId);
        }
        return ResponseEntity.ok(null);
    }

    public ResponseEntity dislike(Long likeUserId) {
        Long userId = UserHolder.getUserId();
//        1.调用api删除喜欢数据 并查询是否相互喜欢
        boolean isFriend = userLikeApi.delete(userId,likeUserId);
//        2.如果相互喜欢 删除user_like表中双向数据 并删除环信好友关系
        Boolean delete = redisTemplate.delete("alreadyLove_" + userId + "_" + likeUserId);
        System.out.println("redis是否删除记录+"+delete);
        System.out.println("alreadyLove_"+userId+"_"+likeUserId);
        if(isFriend){
            friendApi.delete(userId,likeUserId);
//            huanXinTemplate.contactUsers(userId,likeUserId);
//            暂时没有删除环信好友关系的方法
        }
        return ResponseEntity.ok(null);
    }
}

